import storage from '@/utils/storage'
import { createRouter, createWebHistory } from 'vue-router'

import Home from '@/views/home/homePage.vue'
import Layout from '@/views/LayoutPage.vue'
import Login from '@/views/login/longinPage.vue'
const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component: () => import('@/views/login/registerPage.vue')
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/student',
        name: 'student',
        component: () => import('@/views/student/studentPage.vue')
      },
      {
        path: '/teacher',
        name: 'teacher',
        component: () => import('@/views/teacher/teacherPage.vue')
      },
      {
        path: '/class',
        name: 'class',
        component: () => import('@/views/classes/classPage.vue')
      },
      {
        path: '/profile',
        name: 'profile',
        component: () => import('@/views/profile/profilePage.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const path = to.path
  if (path !== '/login' && path !== '/register') {
    const token = storage.get('token')
    if (!token) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})
export default router